package com.zhongli.devplatform.controller.student;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.zhongli.devplatform.bean.SecurityHelper;
import com.zhongli.devplatform.component.FileUtil;
import com.zhongli.devplatform.dto.student.CommitOperationDTO;
import com.zhongli.devplatform.dto.student.StuCommitOperaDTO;
import com.zhongli.devplatform.exception.ServiceException;
import com.zhongli.devplatform.po.common.ReadClazzOperationPO;
import com.zhongli.devplatform.po.common.ReadCommitOperationPO;
import com.zhongli.devplatform.po.teacher.ReadOperationPO;
import com.zhongli.devplatform.po.user.ReadUserPO;
import com.zhongli.devplatform.po.user.ReadUserParentPO;
import com.zhongli.devplatform.po.view.ViewUserPO;
import com.zhongli.devplatform.service.imp.common.ReadClazzOperationService;
import com.zhongli.devplatform.service.imp.student.ReadCommitOperationService;
import com.zhongli.devplatform.service.imp.student.ReadUserParentService;
import com.zhongli.devplatform.service.imp.teacher.ReadOperationService;
import com.zhongli.devplatform.service.imp.user.ReadUserService;
import com.zhongli.devplatform.service.imp.view.ViewUserService;
import com.zhongli.devplatform.utils.BeanCopierUtil;
import com.zhongli.devplatform.utils.DateUtil;
import com.zhongli.devplatform.utils.user.UserUtil;
import com.zhongli.devplatform.vo.student.OperationCommitVO;
import com.zhongli.devplatform.vo.teacher.OperationVO;
import com.zhongli.devplatform.bean.Res;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WuXiCheng
 */
@Api(tags = "学生作业app接口",description = "学生作业app接口",value = "学生作业app接口")
@RestController
@RequestMapping("/operation/commit")
public class CommitOperationController {

    @Autowired
    private ReadCommitOperationService commitOperationService;

    @Autowired
    private ReadUserParentService userParentService;

    @Autowired
    private ReadUserService userService;

    @Autowired
    private ViewUserService viewUserService;

    @Autowired
    private ReadClazzOperationService clazzOperationService;

    @Autowired
    private ReadOperationService operationService;

    @Autowired
    private FileUtil fileUtil;

    @ApiOperation("获取老师需要批改的学生作业")
    @GetMapping("/list")
    public Res list(){
        List<ReadCommitOperationPO> operationPOS = commitOperationService.list();
        List<OperationVO> operationVOS = BeanCopierUtil.copy(operationPOS, OperationVO.class);
        return Res.ok(operationVOS);
    }

    @ApiOperation("老师批改作业")
    @PostMapping("/checkWork")
    public Res checkOperation(@RequestBody CommitOperationDTO commitOperationDTO){
        return commitOperationService.checkOperation(commitOperationDTO);
    }

    @ApiOperation("根据学生id作业id查询学生提交的作业")
    @GetMapping("/getCommitOperation")
    public Res getCommitOperation(@RequestParam("studentId") Integer studentId,@RequestParam("operationId") Integer operationId){
        return commitOperationService.getCommitOperation(studentId,operationId);
    }

    /**
     * 学生提交作业
     * @param commitOperaDTO {@link StuCommitOperaDTO}
     * @return 结果
     */
    @ApiOperation("学生提交作业 param --> commitAnswer 多个图片逗号（,）隔开  学生端")
    @PostMapping("/currentStudentCommitOpera")
    public Res currentStudentCommitOpera(@RequestBody StuCommitOperaDTO commitOperaDTO){
        Integer currentStuId = SecurityHelper.getCurrentUserId();
        ReadCommitOperationPO commitOperationPO = new ReadCommitOperationPO();
        commitOperationPO.setDescription(commitOperaDTO.getDescription());
        commitOperationPO.setStudentId(currentStuId);
        commitOperationPO.setOperationId(commitOperaDTO.getOperationId());
        if (StringUtils.hasLength(commitOperaDTO.getCommitAnswer())){
            List<String> fileList = fileUtil.getFileList(commitOperaDTO.getCommitAnswer(), commitOperaDTO.getFileName());
            if (fileList.size()>1){
                String answer = fileList.stream().map(String::valueOf).collect(Collectors.joining(","));
                commitOperationPO.setAnswer(answer);
            }else {
                commitOperationPO.setAnswer(fileList.get(0));
            }
        }
        commitOperationService.save(commitOperationPO);
        return Res.ok("success");
    }



    /**
     * 查询学生是否以提价作业  false未提交 true提交
     * @param flag false未提交 true提交
     * @return 结果集
     */
    @ApiOperation("获取当前--学生/家长--的的所有作业")
    @GetMapping("/currentStudentAllOpera/{flag}")
    public Res<List<ReadOperationPO>> getCurrentStuOperation(@PathVariable Boolean flag){
        String userRole = UserUtil.getUserRole();
        Integer currentStu = SecurityHelper.getCurrentUserId();
        if("parent".equals(userRole)){
            ReadUserParentPO userParentPO = userParentService.getOne(new QueryWrapper<ReadUserParentPO>()
                    .eq("parent_id",currentStu));
            if (userParentPO == null) return Res.ok(new ArrayList<>());
            currentStu = userParentPO.getUserId();
        }
        ReadUserPO userPO = userService.getById(currentStu);
        List<ReadClazzOperationPO> list =
                clazzOperationService.list(new QueryWrapper<ReadClazzOperationPO>().eq("clazz_id", userPO.getClazzId()));
        List<Integer> operationIds = list
                .stream()
                .map(ReadClazzOperationPO::getOperationId)
                .collect(Collectors.toList());
        List<ReadOperationPO> data = operationService.list(new LambdaQueryWrapper<ReadOperationPO>()
                .in(ReadOperationPO::getId,operationIds).orderByDesc(ReadOperationPO::getCreateTime));

        List<ReadOperationPO> commitOperations = new ArrayList<>();
        Integer finalCurrentStu = currentStu;
        data.forEach(item->{//查询学生是否以提价作业  false未提交 true提交
            ReadCommitOperationPO operationPO = commitOperationService.getOne(new QueryWrapper<ReadCommitOperationPO>()
                    .eq("student_id", finalCurrentStu)
                    .eq("operation_id", item.getId()));
            if (operationPO != null){
                item.setCommitStatus(true);
                item.setStatus(operationPO.getStatus());
                ReadOperationPO operation = operationService.getById(operationPO.getOperationId());
                operation.setStatus(operationPO.getStatus());//老师批改为批改
                commitOperations.add(operation);
            }else {
                item.setCommitStatus(false);
            }
        });
        if (flag) {
            return Res.ok(commitOperations.stream().sorted(Comparator.comparing(ReadOperationPO::getStatus)).collect(Collectors.toList()));
        }
        List<ReadOperationPO> collect  =
                data.stream().filter(item -> !item.getCommitStatus()).collect(Collectors.toList());
        collect.forEach(this::judgmentStatus);
        return Res.ok(collect);
    }



    @ApiOperation("获取当前--学生所选的作业详情")
    @GetMapping("/getOperationByIdAndCurrentStudent/{operationId}")
    public Res<OperationCommitVO> getOperationByIdAndCurrentStudent(@PathVariable Integer operationId){

        String userRole = UserUtil.getUserRole();
        Integer currentStu = SecurityHelper.getCurrentUserId();
        if("parent".equals(userRole)){
            ReadUserParentPO userParentPO = userParentService.getOne(new QueryWrapper<ReadUserParentPO>()
                    .eq("parent_id",currentStu));
            currentStu = userParentPO.getUserId();
        }

        ReadOperationPO operationPO = operationService.getById(operationId);
        OperationCommitVO result = BeanCopierUtil.copy(operationPO, OperationCommitVO.class);
        Integer createUserId = operationPO.getCreateUserId();
        ViewUserPO teacher = viewUserService.getOne(new QueryWrapper<ViewUserPO>().eq("user_id", createUserId));
        assert result != null;
        result.setTeacherName(teacher.getNickName());
        //Integer currentUserId = SecurityHelper.getCurrentUserId();
        ReadCommitOperationPO commitOperationPO = commitOperationService.getOne(new QueryWrapper<ReadCommitOperationPO>()
                .eq("student_id", currentStu)
                .eq("operation_id", operationId));
        if (commitOperationPO != null){
            result.setAnswer(commitOperationPO.getAnswer());
            result.setComment(commitOperationPO.getComment());
        }
        return Res.ok(result);
    }



    /**
     * 设置作业的完成状态
     * @param item  ReadOperationPO
     */
    private void judgmentStatus(ReadOperationPO item){
        Date now = new Date();
        Date startTime = item.getStartTime();
        Date endTime = item.getEndTime();
        Calendar startInstance = Calendar.getInstance();
        startInstance.setTime(startTime);
        Calendar endInstance = Calendar.getInstance();
        endInstance.setTime(endTime);
        if (DateUtil.isEffectiveDate(now, startTime, endTime)){
            item.setIsStart(2);//进行中
        }else if (Calendar.getInstance().before(startInstance)){
            item.setIsStart(1);//未开始
        }else if (Calendar.getInstance().after(endInstance)){
            item.setIsStart(3);//以结束
        }
    }


}
